package wedaex.remote.handler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import wedaex.content.ContentExtractor;
import wedaex.content.ContentSource;
import wedaex.content.RegExpContentExtractor;
import wedaex.helper.SessionUtils;
import wedaex.remote.JsonHandler;

public class RegExpExtractHandler extends JsonHandler {
	protected Log log = LogFactory.getLog(RegExpContentExtractor.class);
	
	@Override
	public String handle(HttpServletRequest request, HttpServletResponse response) throws Exception {
		ContentSource source = SessionUtils.getContentSource(request);
		String name = StringUtils.trim(request.getParameter("extractorName"));
		String re = request.getParameter("regularExpression");
		boolean trimNewLine = StringUtils.equalsIgnoreCase("true", request.getParameter("trimNewLine"));

		ContentExtractor extractor = new RegExpContentExtractor(name, source, re, trimNewLine, new int[]{1});
		SessionUtils.getContentExtractorSet(request).addExtractor(extractor);
		
		if(log.isInfoEnabled()) log.info("Saved: " + extractor);
		String extractedData = extractor.extract();
		if(log.isInfoEnabled()) log.info("Extracted Data: " + extractedData);
		return extractedData;
	}

}
